package vno.sci.mapEditor
{
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.TimerEvent;
	
	import org.osmf.events.TimeEvent;
	
	import vno.fux.res.manager.CommonLoader;
	import vno.fux.res.manager.DataLoader;
	import vno.fux.res.pool.ByteArrayTarget;

	public class MapMarkerAccessible extends Sprite
	{
		private var _marker:Vector.<BuildingInfo>; 
		private var _map:Vector.<Vector.<int>>;
		
		public function MapMarkerAccessible()
		{
			
			var count:int = 0;	
			var lmarker:DataLoader = new DataLoader();
			var markerBa:ByteArrayTarget= new ByteArrayTarget();
			lmarker.load("vno/sci/mapEditor/accessibleMarker001.bin", markerBa, CommonLoader.BINARY);
			lmarker.addEventListener(Event.COMPLETE, function (e:Event):void{trace("1");count++;});
			
			var lmap:DataLoader = new DataLoader;
			var mapBa:ByteArrayTarget = new ByteArrayTarget();
			lmap.load("vno/sci/mapEditor/map.dat", mapBa, CommonLoader.BINARY);
			lmap.addEventListener(Event.COMPLETE, function (e:Event):void{trace("2");count++;});
			
			
			var timer:flash.utils.Timer = new flash.utils.Timer(2000,10);
			var onTimer:Function = function (e:TimeEvent):void
			{
				if(count == 2)
				{
					count++;
					_marker = BuildingInfo.markerToArray(markerBa.data);
					_map = MapEditor.mapToArray(mapBa.data);
					for each (var mark in _marker)
					{
//						moveToSpace(mark as BuildingInfo);
						validate(mark as BuildingInfo);
					}
					var item:BuildingInfo = _marker[1];
					var show:MapMarker = new MapMarker();
					show._inner.loadBinary(BuildingInfo.arrayToBinary(_marker));
					addChild(show);
				}
			}
			var validate:Function = function(mark:BuildingInfo):void
			{
				if(test(mark))
					return;
				else trace(mark.s);
			}
			var test:Function = function (mark:BuildingInfo):Boolean
			{
				var x:int = mark.x/20;
				var y:int = mark.y/20;
				if(_map[x][y] != 1)
					return true;
				else return false;
			}
			var moveToSpace:Function = function (mark:BuildingInfo):void
			{
				var range:int = 1000;
				var loop:int = 0;
				var ori_x:Number = mark.x;
				var ori_y:Number = mark.y;
				while(loop < range)
				{
					loop++;
					mark.x += loop;
					if(test(mark))
						break;
					mark.y += loop;
					if(test(mark))
						break;
					loop++;
					mark.x -= loop;
					if(test(mark))
						break;
					mark.y -= loop;
					if(test(mark))
						break;					
				}
				if(loop >= range)
				{
					mark.x = ori_x;
					mark.y = ori_y;
					trace(mark.s);
				}
			}
			timer.addEventListener(TimerEvent.TIMER, onTimer);
			timer.start();
		}
	}
}